package network;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import command.protobuf.MessageBufProtoBuf.*;

/**
 * connection is divided into two types: incoming and outcoming 1
 * InComingConnection will reads data from the connection util the connection is
 * closed by the sender. 2 OutComingConnection can always send data util it get
 * an close message to send. Then it will close the socket, which causes the
 * InComingConnection to be closed;
 * 
 * @author xiafan
 * 
 */
public class InComingTcpConnection extends Thread {
	private static final Logger logger = LoggerFactory
			.getLogger(InComingTcpConnection.class);
	private static RpcMessage.Builder builder = RpcMessage.newBuilder();
	private Socket socket = null;

	public InComingTcpConnection(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			DataInputStream input = new DataInputStream(socket.getInputStream());
			while (true) {
				if (!socket.isConnected()) {
					logger.debug(socket + " closed");
					break;
				}
				RpcMessage message = RpcMessage.parseFrom(input);
				MessageService.instance().processMessage(message, socket);
			}
		} catch (EOFException e) {

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				socket.shutdownInput();
				//socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			socket = null;
		}
	}

}
